package org.jobtask.schedule;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.text.BadLocationException;

import org.jobtask.config.ResourceMessages;
import org.jobtask.config.SystemIdentification;
import org.jobtask.io.LogIO;

public class TaskFlow {

	private ProcessBuilder pb=null;
	private Process process=null;
	private Runtime run=null;
	private String cmd="";
	
	public TaskFlow(String... command){
		run=Runtime.getRuntime();
		cmd=command[0]+" "+command[1];
		pb=new ProcessBuilder(command);
	}
	
	public boolean begin(){
		boolean isStart=true;
		String dir=System.getProperty("user.dir");
			try {
				if(SystemIdentification.assertOS().equals("windows")){
					process=pb.start();
				}else{
					process=run.exec(cmd,null,new File(dir));
				}
			} catch (IOException e) {
				isStart=false;
				e.printStackTrace();
			}
		return isStart;
	}
	
	public void destroy(){
		if(this.process!=null){
			this.process.destroy();
		}
	}
	
	private boolean isSeccess=true;
	
	public boolean isSeccess() {
		return isSeccess;
	}

	public boolean monitor(JobTask job){
		isSeccess=false;
		LogIO logio=new LogIO();
		String msg="";
		try {
			InputStream fis = process.getInputStream(); 
            BufferedReader br = new BufferedReader(new InputStreamReader(fis)); 
            String line = null; 
            job.setState(JobState.RUNING);
            job.clearLog(true);
            job.addLog(" "+ResourceMessages.getString("TaskFlow.0")+"\n");
			SimpleDateFormat format=new SimpleDateFormat("[yyyy-MM-dd(HHmmss)]");
			logio.openLogChannel("logs/"+job.getSequece()+format.format(new Date())+".log");
            while ((line = br.readLine()) != null) {
//            	 if(line.startsWith("##$")&&line.endsWith("$##")){
//            		 ExceptionJobStack.putPID(job.getSequece(), new KeyValue(line.substring(line.indexOf("$")+1,line.lastIndexOf("$")),new Date()));
//            	 }
            	  logio.saveLog(line);
                  job.addLog(line);
            } 
            int isExit=process.waitFor();
            int flag=process.exitValue();
            if(isExit==0&&flag==0){
               isSeccess=true;
               msg=ResourceMessages.getString("TaskFlow.1");
            }else{
               msg="else"+ResourceMessages.getString("TaskFlow.2");
               ExceptionJobStack.addStopJob(job);
               job.addLog("\n"+ExceptionJobStack.getJobSize()+"\n");
            }
		} catch (IOException e) {
			 ExceptionJobStack.addStopJob(job);
			 msg="IOException:"+ResourceMessages.getString("TaskFlow.2");
			 e.printStackTrace();
		} catch (InterruptedException e) {
			ExceptionJobStack.addStopJob(job);
			msg="InterruptedException:"+ResourceMessages.getString("TaskFlow.2");
			e.printStackTrace();
		} catch (BadLocationException e) {
			ExceptionJobStack.addStopJob(job);
			msg="BadLocationException:"+ResourceMessages.getString("TaskFlow.2");
			e.printStackTrace();
		}finally{
			try {
				job.addLog("\n"+msg+"\n");
			} catch (BadLocationException e) {
				e.printStackTrace();
			}
			logio.closeLogChannel();
		}
//		ExceptionJobStack.removePID(job.getSequece());
		return isSeccess;
	}
}

